<template>
  <div class="layui-container fly-marginTop">
    <div class="fly-panel fly-panel-user" pad20>
      <div class="layui-tab layui-tab-brief" lay-filter="user">
        <ul class="layui-tab-title">
          <li class="layui-this">登入</li>
          <li>
            <router-link :to="{name: 'reg'}">注册</router-link>
          </li>
        </ul>
        <div class="layui-form layui-tab-content" id="LAY_ucm" style="padding: 20px 0;">
          <validation-observer ref="observer" v-slot="{validate}">
            <div class="layui-tab-item layui-show">
              <div class="layui-form layui-form-pane">
                <form method="post">
                  <div class="layui-form-item">
                    <label for="L_email" class="layui-form-label">用户名</label>
                    <validation-provider name="email" rules="required|email" v-slot="{errors}">
                      <div class="layui-input-inline">
                        <input
                          id="L_email"
                          type="text"
                          name="username"
                          v-model="username"
                          autocomplete="off"
                          class="layui-input"
                          placeholder="请输入用户名"
                        />
                      </div>
                      <div class="layui-form-mid">
                        <span style="color: #c00;">{{errors[0]}}</span>
                      </div>
                    </validation-provider>
                  </div>
                  <div class="layui-form-item">
                    <label for="L_pass" class="layui-form-label">密码</label>
                    <validation-provider name="password" rules="required|min:6" v-slot="{errors}">
                      <div class="layui-input-inline">
                        <input
                          id="L_pass"
                          type="password"
                          name="password"
                          v-model="password"
                          autocomplete="off"
                          class="layui-input"
                          placeholder="请输入密码"
                        />
                      </div>
                      <div class="layui-form-mid">
                        <span style="color: #c00;">{{errors[0]}}</span>
                      </div>
                    </validation-provider>
                  </div>
                  <div class="layui-form-item">
                    <validation-provider
                      name="code"
                      ref="codefield"
                      rules="required|length:4"
                      v-slot="{errors}"
                    >
                      <div class="layui-row">
                        <label for="L_vercode" class="layui-form-label">验证码</label>
                        <div class="layui-input-inline">
                          <input
                            type="text"
                            id="L_vercode"
                            name="code"
                            v-model="code"
                            placeholder="请输入验证码"
                            class="layui-input"
                            autocomplete="off"
                          />
                        </div>
                        <div>
                          <span class="svg" style="color:#c00;" @click="_getCaptcha" v-html="svg"></span>
                        </div>
                        <div class="layui-form-mid">
                          <span style="color: #c00;">{{errors[0]}}</span>
                        </div>
                      </div>
                    </validation-provider>
                  </div>
                  <div class="layui-form-item">
                    <button class="layui-btn" type="button" @click="validate().then(submit)">立即登录</button>
                    <span style="padding-left: 20px;">
                      <router-link :to="{name: 'forget'}">忘记密码</router-link>
                    </span>
                  </div>
                </form>
              </div>
            </div>
          </validation-observer>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getCaptcha, login } from '@/api/login'
import { ValidationProvider, ValidationObserver } from 'vee-validate'
import { mapGetters, mapMutations } from 'vuex'
import uuid from 'uuid/v4'
export default {
  name: 'app',

  data() {
    return {
      username: '',
      password: '',
      code: '',
      svg: ''
    }
  },
  computed: {
    ...mapGetters(['sid'])
  },
  mounted() {
    window.vue = this
    this._initSid()
    this._getCaptcha()
  },
  methods: {
    async _getCaptcha() {
      const res = await getCaptcha(this.sid)
      if (res.code === 200) {
        this.svg = res.data
      }
    },
    async submit() {
      const isValid = await this.$refs.observer.validate()
      if (!isValid) {
        return
      }
      login({
        username: this.username,
        password: this.password,
        code: this.code,
        sid: this.sid
      })
        .then(result => {
          if (result.code === 200) {
            const { token, data: userInfo } = result
            this.setToken(token)
            this.setUserInfo(result.data)
            this.setIsLogin(true)
            this.username = ''
            this.password = ''
            this.code = ''
            requestAnimationFrame(() => {
              this.$refs.observer.reset()
            })
            this.$router.push({ name: 'index' })
          } else if (result.code === 10014) {
            this.$refs.codefield.setErrors([result.message])
          } else if (result.code === 10004) {
            this.$alert(result.message)
          } else if (result.code === 10003) {
            this.$alert(result.message)
          }
        })
        .catch(error => {
          if (error.code === 500) {
            this.$alert('用户名或密码错误，请检查！')
          } else {
            this.$alert('服务器错误')
          }
        })
    },
    _initSid() {
      let sid = ''
      if (localStorage.getItem('sid')) {
        sid = localStorage.getItem('sid')
      } else {
        sid = uuid()
        localStorage.setItem('sid', sid)
      }
      this.setSid(sid)
    },
    ...mapMutations({
      setSid: 'SET_SID',
      setToken: 'SET_TOKEN',
      setIsLogin: 'SET_ISLOGIN',
      setUserInfo: 'SET_USER_INFO'
    })
  },
  components: {
    ValidationObserver,
    ValidationProvider
  }
}
</script>

<style lang="scss" scoped>
#app {
  background: #dcdcdc;
}
.layui-container {
  background: #ffffff;
}
input {
  width: 190px;
}

.imooc-link {
  margin-left: 10px;
  &:hover {
    color: #009688;
  }
}

.svg {
  position: relative;
  top: -6px;
}

.error {
  color: red;
}
</style>